package com.enqualcomm.kids.network;

import android.graphics.Bitmap;
import android.os.Handler;

import com.android.volley.BuildConfig;
import com.android.volley.socket.SocketStack;
import com.enqualcomm.kids.activities.TerminalInfoActivity;
import com.enqualcomm.kids.bean.StringMessage;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;

import common.utils.MyLogger;
import de.greenrobot.event.EventBus;


/**
 * Created by yinzhiqun on 2015/10/17.
 *
 */
public class RoundImageRunnable implements Runnable{
    private String newImagePath;
    private Bitmap bitmap;
    private String userterminalid;
    private Handler mHandler;
    private String ip;

    public RoundImageRunnable(Bitmap bitmap, String newImagePath, String userterminalid, Handler mHandler,String ip) {
        this.bitmap = bitmap;
        this.newImagePath = newImagePath;
        this.userterminalid = userterminalid;
        this.mHandler = mHandler;
        this.ip = ip;
    }

    @Override
    public void run() {
//        MyBitMapUtil.roundAndSaveBitmap(bitmap, newImagePath);//实际上并没有剪裁，逗比ios不会弄
        int code ;
        if (BuildConfig.Secret){
            code = uploadPicSecret();
        }else{
            code = uploadPicNormal();
        }

        if (code==100){
            new UserTerminalDefault(userterminalid).setIconPath(newImagePath);//保存新头像的路径

            mHandler.sendEmptyMessage(TerminalInfoActivity.ROUND_IMAGE_COMPLETE);
            EventBus.getDefault().post(new StringMessage(StringMessage.ICON_UPDATED));
        }else{
            mHandler.sendEmptyMessage(TerminalInfoActivity.UPLOAD_PIC_FAILED);
        }
    }

    private int uploadPicSecret() {
        String userkey = new AppDefault().getUserkey();
        Socket socket = null;
        int resultCode = -1;
        try {
            {
                socket = new Socket(ip, 11647);
                socket.setSoTimeout(15 * 1000);

                File image = new File(newImagePath);
                int fileLength = (int) image.length();
                int totalLength = 305 + fileLength;

                byte[] fileBuffer = new byte[fileLength];
                FileInputStream in = new FileInputStream(image);
                in.read(fileBuffer);
                in.close();

    //			System.out.println("上传图片，大小："+filelen);
                byte[] userkeyBuffer = userkey.getBytes();
                byte[] userterminalidBuffer = userterminalid.getBytes();

                byte[] totalBuffer = new byte[totalLength];
                totalBuffer[0] = 2;
                System.arraycopy(userkeyBuffer, 0, totalBuffer, 1, 32);
                System.arraycopy(userterminalidBuffer, 0, totalBuffer, 33, 16);
                System.arraycopy(fileBuffer, 0, totalBuffer, 305, fileLength);

                SocketStack.send(socket, totalBuffer);
            }

            byte[] receive = SocketStack.receive(socket);
            if (receive[0]==2){
                MyLogger.jLog().i("头像上传成功");
                resultCode = 100;
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultCode;
    }

    private int uploadPicNormal() {
        String userkey = new AppDefault().getUserkey();
        Socket socket = null;
        int resultCode = -1;
        try {
            socket = new Socket(ip, 11647);
            socket.setSoTimeout(15 * 1000);
            DataOutputStream dao = new DataOutputStream(socket.getOutputStream());

            int len;
            byte[] filebuf = null;
            long filelen = 0;
            File file = new File(newImagePath);
            if (file != null) {
                filelen = file.length();

                filebuf = new byte[(int) filelen];
                FileInputStream in = new FileInputStream(newImagePath);
                in.read(filebuf);
                in.close();
            }
//			System.out.println("上传图片，大小："+filelen);


            len = 1 + 32 + 16 + 256;
            byte[] blen = new byte[4];
            byte[] sbuf = new byte[len + 4];

            len += filelen;
            for (int i = 3; i >= 0; i--) {
                byte b = (byte) ((len >> i * 8));

                blen[Math.abs(i - 3)] = b;
            }
//			//System.out.println(byteToInt2(blen) + "------");
            System.arraycopy(blen, 0, sbuf, 0, 4);
            sbuf[4] = 2;//new Integer(2).byteValue();
            byte[] buserkey = userkey.getBytes();
            byte[] busertemid = userterminalid.getBytes();
            System.arraycopy(buserkey, 0, sbuf, 5, 32);
            System.arraycopy(busertemid, 0, sbuf, 5 + 32, 16);

            byte[] imsgename  = newImagePath.getBytes();

            System.arraycopy(imsgename, 0, sbuf, 5 + 32 + 16, imsgename.length);
            dao.write(sbuf);
            dao.write(filebuf);

            DataInputStream dis = new DataInputStream(socket.getInputStream());

            byte[] b1 = new byte[4];
            byte[] b2 = new byte[1];
            dis.read(b1);
            dis.read(b2);

//			//System.out.println(String.valueOf(b2[0]));

            dis.close();
            dao.close();
            socket.close();
            if ("2".equals(String.valueOf(b2[0]))) {
                MyLogger.jLog().i("头像上传成功");
                resultCode = 100;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultCode;
    }
}
